#include "StdAfx.h"
#include "DataHandler.h"

#include "sqlite3.h"
#include "ConsoleLog.h"


CDataHandler::CDataHandler(const char* filename)
: m_pDatabase(NULL)
{
    if (SQLITE_OK != sqlite3_open(filename, &m_pDatabase))
    {
        sqlite3_close(m_pDatabase);
        ASSERT(FALSE);
    }
}

CDataHandler::~CDataHandler(void)
{
    sqlite3_close(m_pDatabase);
    m_pDatabase = NULL;
}

int CDataHandler::Execute(const char* sql)
{
    CCriticalLock lock(&m_criticalSection);
    char *zErrMsg = 0;
    if (SQLITE_OK != sqlite3_exec(m_pDatabase , sql , 0 , 0 , &zErrMsg))
    {
        CLog::Info(zErrMsg);
        return -1;
    }

    return 0;
}

int CDataHandler::Query( const CString& sql, char *** azResult, int* nRow, int* nColumn )
{
    CCriticalLock lock(&m_criticalSection);
    char *zErrMsg = 0;
    if (SQLITE_OK != sqlite3_get_table( m_pDatabase, sql, azResult, nRow, nColumn, &zErrMsg ))
    {
        CLog::Info(zErrMsg);
        return -1;
    }

    return 0;
}

sqlite3_stmt *CDataHandler::Prepare(const char* sql)
{
    CCriticalLock lock(&m_criticalSection);
    sqlite3_stmt *stmt = 0;
    const char *zErrMsg = 0;
    if (SQLITE_OK != sqlite3_prepare_v2(m_pDatabase , sql , strlen(sql) , &stmt, &zErrMsg))
    {
        CLog::Info(zErrMsg);
        return NULL;
    }

    return stmt;
}

